package com.com.typhoon.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.TextCodec;

import javax.xml.bind.DatatypeConverter;
import java.time.Instant;
import java.util.Date;

/**
 * @author shuya | dongfeng.zdf@alibaba-inc.com
 * @description
 * @date 2018/10/25 下午5:44
 * @description
 * @modified by
 * @since V2.0.0
 */
public class JwtUtil {

   public static final String SALT = "abcd@#$%";

    public static Claims parseJwt(String jwt,String salt) {
        Claims claims = Jwts.parser()
                .setSigningKey(DatatypeConverter.parseBase64Binary(salt))
                .parseClaimsJws(jwt).getBody();
        return claims;
    }

    public static Jwt parseJwts(String jwt,String salt) {
        try
        {
           Jwt result  = Jwts.parser()
                    .setSigningKey(DatatypeConverter.parseBase64Binary(salt))
                    .parse(jwt);
            return result;
        }
        catch(Exception ex)
        {
            return null;
        }
    }



    public static  String generateJwt(String username,String userId,long tTLMillis, String salt) {
        String jws = Jwts.builder()
                .setHeaderParam("typ","JWT")
                .setIssuer("system")
                .claim("username", username)
                .claim("userId", userId)
                // Fri Jun 24 2016 15:33:42 GMT-0400 (EDT)
                .setIssuedAt(Date.from(Instant.ofEpochSecond(System.currentTimeMillis() / 1000)))
                // Sat Jun 24 2116 15:33:42 GMT-0400 (EDT)
                .setExpiration(Date.from(Instant.ofEpochSecond(System.currentTimeMillis() / 1000 + tTLMillis)))
                .signWith(
                        SignatureAlgorithm.HS256,
                        TextCodec.BASE64.decode(salt)
                )
                .compact();
        return jws;
    }

    public static void main(String[] args) {
        String salt = "abcd@#$%";
        String str = generateJwt("admin","1",30000L,salt);
        System.out.println(str);
        Claims claims = parseJwt(str,salt);
        System.out.println(claims);
        System.out.println(parseJwts(str,salt));
    }

}
